import { ipcMain } from "electron"
import reloadHttp from '../reloadHttp'
import { writeProxyFileData, readProxyFileData } from '../../main/readFile/index'
import { getIPAddress } from '../findIpConfig'

const initIpcMain = (mainWindow: any) => {
  // 监听屏幕缩小
  ipcMain.on('window-min', () => {
    mainWindow.minimize()
  })

  ipcMain.on('window-max', () => {
    // 如果已经是最大化窗口就还原
    mainWindow.isMaximized() ? mainWindow.restore(): mainWindow.maximize()
  })

  ipcMain.on('window-close', () => {
    mainWindow.close()
  })

  // 设置请求代理
  ipcMain.on('http-proxy', async (event, data) => {
    // 写入文件到本地
    let rjs = await writeProxyFileData(data)
    if(rjs){
      event.sender.send('http-proxy-error', rjs)
      return
    }
    let res = await reloadHttp(data);
    event.sender.send('http-proxy-error', res)
  })

  // 读取本地文件
  ipcMain.on('read-proxy-to-file', async (event, _data)=> {
    let res = await readProxyFileData();
    event.sender.send('send-proxy-to-file', res)
  })

  // 获取当前IP地址
  ipcMain.on('ip-config', (event, _data)=> {
    let res = getIPAddress();
    event.sender.send('to-ip-config', res)
  })

}

export default initIpcMain